package com.zydl.f9164m.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.zydl.f9164m.R;
import com.zydl.f9164m.basis.BasisFragment;
import com.zydl.f9164m.basis.Constants;
import com.zydl.f9164m.bean.ParamListData;
import com.zydl.f9164m.eventbus.FragmentChangeMessage;
import com.zydl.f9164m.util.CountDown;
import com.zydl.f9164m.util.EditTextUtil;
import com.zydl.f9164m.util.SoftKeyBoardListener;
import com.zydl.f9164m.util.SubstringUtil;
import com.zydl.f9164m.view.PopHandle;
import com.suke.widget.SwitchButton;

import org.greenrobot.eventbus.EventBus;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.BleUtils;
import my.LogUtil;

public class CenterFragment extends BasisFragment {

    static CenterFragment fragment;

    public static CenterFragment newInstance() {
        if (fragment == null) {
            fragment = new CenterFragment();
        }
        return fragment;
    }

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    MyAdapter adapter;
    ArrayList<ParamListData> centerList;
    ArrayList<ParamListData> originalList;
    ArrayList<String> mainSvrPassWayList;
    ArrayList<String> mainSvrAddressList;
    ArrayList<String> bkSvrPassWayList;
    ArrayList<String> bkSvrAddressList;
    public static int SUBMIT = 75;

    private boolean isFinish = false;

    private CountDown mCountDownTimer;
    private static final long MAX_TIME = 11 * 1000;
    private StringBuffer saveResult = new StringBuffer();

    private String server = "";
    private PopHandle popHandle;

    private int subPosition = 0;
    private Handler submitHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 75://75提交
                    isFinish = false;
                    if (subPosition < centerList.size()) {
                        initSettingSaveThred(subPosition);
                        subPosition++;
                    } else {
                        BleUtils.stopNotify();
                        isFinish = true;
                        originalList.clear();
                        originalList.addAll(centerList);
                        dismissProgress();
                        mCountDownTimer.cancel();
                        if (!TextUtils.isEmpty(saveResult.toString())) {
                            if (popHandle == null) {
                                popHandle = new PopHandle(mContext, "tips_fail", "错误信息", saveResult.toString());
                            }
                            popHandle.show();
                        } else {
                            showToast("保存成功");
                        }
                    }
                    break;
                case 76:  //检查是否传输完毕
                    if (!isFinish) {
                        showToast("设置失败，请重试");
                        dismissProgress();
                        BleUtils.stopNotify();
                    }
                    break;
            }

        }
    };

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            LogUtil.d("终端fragment显示");
        } else {
            //相当于OnPause()
            LogUtil.d("终端fragment隐藏");
        }
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_center);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        initCountDownTimer();
    }

    public void initCountDownTimer() {
        mCountDownTimer = new CountDown();
        mCountDownTimer.setMillisInFuture(MAX_TIME);
        mCountDownTimer.setCountdownInterval(1000);
        mCountDownTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(Constants.CHECK_FINISH);
                //这时候可以做30秒的计时操作
//                submitHandler.sendEmptyMessageDelayed(Constants.CHECK_FINISH, 20000);
//                          submitHandler.postDelayed(Constants.SUBMIT,20000);   //20秒后执行
            }

            @Override
            public void onTick(long millisUntilFinished) {
//                mTimerTv.setText(TimeTools.getCountTimeByLong(millisUntilFinished));
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        centerList = new ArrayList<>();
        originalList = new ArrayList<>();
        mainSvrPassWayList = new ArrayList<>();
        mainSvrAddressList = new ArrayList<>();
        bkSvrPassWayList = new ArrayList<>();
        bkSvrAddressList = new ArrayList<>();
    }

    private String atShowString;

    public void setList(String sMsgObjString, int type) {
        centerList.clear();
        mainSvrPassWayList.clear();
        mainSvrAddressList.clear();
        bkSvrPassWayList.clear();
        bkSvrAddressList.clear();
        if (!TextUtils.isEmpty(sMsgObjString)) {
            atShowString = sMsgObjString;
            //中心服务器个数
            String centreNum = SubstringUtil.subString(sMsgObjString, "Total Servers:");
            centerList.add(new ParamListData("中心服务器个数", 2, "" + centreNum, "AT+SVRCNT"));

            List<String> serverParaList = Arrays.asList(getResources().getStringArray(R.array.serverPara));
            centerList.add(new ParamListData("服务器", 1, "" + serverParaList.get(0), serverParaList, "AT+BKSVRTYP"));

            List<String> aisleList = Arrays.asList(getResources().getStringArray(R.array.aisle));
            centerList.add(new ParamListData("服务器通道", 1, "" + getPassWay(sMsgObjString, "主服务器"), aisleList, "", ""));
            server = "主服务器";
            centerList.add(new ParamListData("服务器地址", 2, "" + getAddress(sMsgObjString, "主服务器"), "", ""));

            String dns1 = SubstringUtil.subString(sMsgObjString, "Dns1:");
            centerList.add(new ParamListData("首选DNS服务器", 2, "" + dns1, "AT+DNS", ""));

            String dns2 = SubstringUtil.subString(sMsgObjString, "Dns2:");
            centerList.add(new ParamListData("备用DNS服务器", 2, "" + dns2, "AT+BKDNS"));
            String apn = SubstringUtil.subString(sMsgObjString, "APN:");
            centerList.add(new ParamListData("APN", 2, "" + apn, "AT+APN"));
            String dialNo = SubstringUtil.subString(sMsgObjString, "Dial No:");
            centerList.add(new ParamListData("APN拨号号码", 2, "" + dialNo, "AT+CENT"));
            String userName = SubstringUtil.subString(sMsgObjString, "User Name:");
            centerList.add(new ParamListData("APN用户名", 2, "" + userName, "AT+DNAME"));
            String apnPwd = SubstringUtil.subString(sMsgObjString, "Password:");
            centerList.add(new ParamListData("APN密码", 2, "" + apnPwd, "AT+DPWD"));
            String reConnInt = SubstringUtil.subString(sMsgObjString, "Re conn Int:");
            centerList.add(new ParamListData("重连间隔", 2, "" + reConnInt, "AT+RECINT"));
            String heartInt = SubstringUtil.subString(sMsgObjString, "Heart Int:");
            centerList.add(new ParamListData("心跳间隔", 2, "" + heartInt, "AT+POLLTIME"));

            if (type == Constants.AT_FROM_DEVICE) {
                originalList.addAll(centerList);
            }
        }
        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);
    }

    private String getPassWay(String sMsgObjString, String key) {
        //例子sMsgObjString =  Main Svr's 1:TCP,120.42.46.98:5003
        //中心地址
        String keyWord = "";
        switch (key) {
            case "主服务器":
                keyWord = "Main Svr's 1:";
                break;
            case "第1服务器":
                keyWord = "Main Svr's 2:";
                break;
            case "第2服务器":
                keyWord = "Main Svr's 3:";
                break;
            case "第3服务器":
                keyWord = "Main Svr's 4:";
                break;
            case "主备份服务器":
                keyWord = "BK Svr's 1:";
                break;
            case "第1备份服务器":
                keyWord = "BK Svr's 2:";
                break;
            case "第2备份服务器":
                keyWord = "BK Svr's 3:";
                break;
            case "第3备份服务器":
                keyWord = "BK Svr's 4:";
                break;
        }
        String dataString = SubstringUtil.subString(sMsgObjString, "" + keyWord);    //dataString = TCP,120.42.46.98:5003
        String passWay = SubstringUtil.getStringBeforeKey(dataString, ",");
        return passWay;
    }

    private String getAddress(String sMsgObjString, String key) {
        //例子sMsgObjString =  Main Svr's 1:TCP,120.42.46.98:5003
        String keyWord = "";
        switch (key) {
            case "主服务器":
                keyWord = "Main Svr's 1:";
                break;
            case "第1服务器":
                keyWord = "Main Svr's 2:";
                break;
            case "第2服务器":
                keyWord = "Main Svr's 3:";
                break;
            case "第3服务器":
                keyWord = "Main Svr's 4:";
                break;
            case "主备份服务器":
                keyWord = "BK Svr's 1:";
                break;
            case "第1备份服务器":
                keyWord = "BK Svr's 2:";
                break;
            case "第2备份服务器":
                keyWord = "BK Svr's 3:";
                break;
            case "第3备份服务器":
                keyWord = "BK Svr's 4:";
                break;
        }
        String dataString = SubstringUtil.subString(sMsgObjString, "" + keyWord);    //dataString = TCP,120.42.46.98:5003
        String address = SubstringUtil.getStringAfterKey(dataString, ",");
        return address;
    }

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public MyAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_pass_way_base_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.list_item.setTag(position);
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return centerList == null ? 0 : centerList.size();
        }


        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.list_item)
            LinearLayout list_item;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.edit_text)
            EditText editText;
            @BindView(R.id.img_spanner)
            ImageView imgSpanner;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.switch_btn)
            SwitchButton switchBtn;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
                EditTextUtil.setEditTextNoEmoji(editText);
            }

            public void bind(int position) {
                ParamListData centerListData = centerList.get(position);
                tvName.setText(centerListData.getName());
                switch (centerListData.getType()) {
                    case 1: //spinner
                        editText.setText("" + (TextUtils.isEmpty(centerListData.getValue()) ? centerListData.getKey() : centerListData.getValue()));
                        editText.setHint("请选择" + centerListData.getName());
                        imgSpanner.setVisibility(View.VISIBLE);
                        tvUnit.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        editText.setEnabled(false);//不可编辑
                        list_item.setBackgroundResource(R.color.white);
                        break;
                    case 2:  // edit
                        editText.setText("" + centerListData.getValue());
                        editText.setHint("请输入" + centerListData.getName());
                        tvUnit.setVisibility(View.GONE);
                        imgSpanner.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        editText.setEnabled(true);//可编辑
                        editText.setVisibility(View.VISIBLE);
                        list_item.setBackgroundResource(R.color.white);
                        break;
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        int curPosition = getAdapterPosition();
                        ParamListData data = centerList.get(curPosition);
                        centerList.set(curPosition, new ParamListData(data.getName(), data.getType(), s.toString(), data.getValues(), data.getAction(), data.getKey(), data.getIsOpen(), data.getUnit()));
                    }
                });
                imgSpanner.setTag(position);
            }

            @OnClick(R.id.img_spanner)
            public void showSpanner(View v) {
                SoftKeyBoardListener.hideKeyboard(getActivity());
                final int position = (int) v.getTag();
                final ParamListData centerData = centerList.get(position);
                OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        String optionValue = centerData.getValues().get(options1);
                        editText.setText(optionValue);
                        centerList.get(position).setValue(optionValue);
                        switch (centerData.getName()){
                            case "服务器":
                                server = optionValue;
                                for (int i = 0; i < centerList.size(); i++) {
                                    switch (centerList.get(i).getName()) {
                                        case "服务器通道":
                                            String key = getPassWay(atShowString, optionValue);
                                            centerList.get(i).setValue("" + key);
                                            adapter.notifyItemChanged(i);
                                            break;
                                        case "服务器地址":
                                            centerList.get(i).setValue("" + getAddress(atShowString, optionValue));
                                            adapter.notifyItemChanged(i);
                                            break;
                                    }
                                }
                                break;
                                case "服务器通道":
                                    EventBus.getDefault().post(new FragmentChangeMessage(optionValue));
                                    break;
                        }

                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .build();
                pickerView.setPicker(centerData.getValues());
                pickerView.show();
            }
        }
    }


    @OnClick(R.id.btn_save)
    public void save() {
        final StringBuffer atShowResult = new StringBuffer();
        showLoading();
        BleUtils.notify(mContext,new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                saveResult.setLength(0);
                subPosition = 0;
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }

            @Override
            public void onNotifyFailure(BleException exception) {
                BleLog.d("下发设置打开通知操作失败");
            }

            @Override
            public void onNotifyFailure(String message) {
                showToast(message);
                dismissProgress();
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                for (Byte a : data) {
                    atShowResult.append(String.format("%02X", a));
                }
                String sMes = HexUtil.hexStringToString(atShowResult.toString());
                if (sMes.contains("OK")) {
                    originalList.set(subPosition - 1, centerList.get(subPosition - 1));
                    atShowResult.setLength(0);
                    submitHandler.sendEmptyMessage(Constants.SUBMIT);
                }else if(sMes.contains("ERROR")){
                    atShowResult.setLength(0);
                    onError();
                }
            }

            @Override
            public void onError() {
                saveResult.append(centerList.get(subPosition - 1).getName() + "保存失败" + "\r\n");
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }

            @Override
            public void onReconSuc(String message) {
                dismissProgress();
                showToast(message);
            }
        });
    }

    public void initSettingSaveThred(final int position) {
        String url = getBlueToothUrl(centerList.get(position));
        String centerName = centerList.get(position).getName();
        if (centerName.equals("服务器")) {
            submitHandler.sendEmptyMessage(Constants.SUBMIT);
            return;
        }
        if (TextUtils.isEmpty(url) && (centerName.equals("重连间隔") || centerName.equals("首选DNS服务器") || centerName.equals("备用DNS服务器"))) {
            showToast(centerName + "错误");
            return;
        }
        if (TextUtils.isEmpty(url)) {
            url = "";
        }

        String originalurl = getBlueToothUrl(originalList.get(position));
        if (TextUtils.isEmpty(originalurl)) {
            originalurl = "";
        }
        if (originalurl.equals(url)) {
            submitHandler.sendEmptyMessage(Constants.SUBMIT);
            return;
        }

        mCountDownTimer.start();

        final String toSet = url;
        BleUtils.write(toSet, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                if (current == total) {

                }
            }

            @Override
            public void onWriteFailure(final BleException exception) {
                saveResult.append(centerList.get(position).getName() + "下发失败" + "\r\n");
            }
        });


    }


    private String getBlueToothUrl(ParamListData data) {
        String name = data.getName();
        String at = data.getAction();
        String value = (data.getValue() == null) ? data.getKey() : data.getValue();
        if (TextUtils.isEmpty(value)) {
            value = "";
        }

        switch (name) {
            case "首选DNS服务器":
            case "备用DNS服务器":
                if (value.length() < 7) {
                    return "";
                }
                break;
            case "心跳间隔":
                if (canParseInt(value)) {
                    int num = Integer.valueOf(value);
                    if (num > 65535) {
                        return "";
                    }
                } else {
                    return "";
                }
                break;
            case "重连间隔":
                if (canParseInt(value)) {
                    int num = Integer.valueOf(value);
                    if (num > 65535 || num < 30) {
                        return "";
                    }
                } else {
                    return "";
                }
                break;
            case "服务器通道":
                at = getPassWayAction();
                break;
            case "服务器地址":
                at = getAddressAction();
                break;
        }


        String a = "";
        try {
            a = HexUtil.chineseWordToGbk((at + "=" + value)) + "0D0A";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return a;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        submitHandler.removeCallbacksAndMessages(null);
    }


    public static boolean canParseInt(String str) {
        if (TextUtils.isEmpty(str)) { //验证是否为空
            return false;
        }
        return str.matches("-?[0-9]+.*[0-9]*");
//        return str.matches("\\d+"); //使用正则表达式判断该字符串是否为数字，第一个\是转义符，\d+表示匹配1个或 //多个连续数字，"+"和"*"类似，"*"表示0个或多个
    }

    private String getPassWayAction(){
        String at = "";
        switch (server){
            case "主服务器":
                at = "AT+SVRTYP";
                break;
            case "第1服务器":
                at = "AT+SVRTYP1";
                break;
            case "第2服务器":
                at = "AT+SVRTYP2";
                break;
            case "第3服务器":
                at = "AT+SVRTYP3";
                break;
            case "主备份服务器":
                at = "AT+BKSVRTYP";
                break;
            case "第1备份服务器":
                at = "AT+BKSVRTYP1";
                break;
            case "第2备份服务器":
                at = "AT+BKSVRTYP2";
                break;
            case "第3备份服务器":
                at = "AT+BKSVRTYP3";
                break;
        }
        return at;
    }
    private String getAddressAction(){
        String at = "";
        switch (server){
            case "主服务器":
                at = "AT+IPAD";
                break;
            case "第1服务器":
                at = "AT+IPAD1";
                break;
            case "第2服务器":
                at = "AT+IPAD2";
                break;
            case "第3服务器":
                at = "AT+IPAD3";
                break;
            case "主备份服务器":
                at = "AT+IPSEC";
                break;
            case "第1备份服务器":
                at = "AT+IPSEC1";
                break;
            case "第2备份服务器":
                at = "AT+IPSEC2";
                break;
            case "第3备份服务器":
                at = "AT+IPSEC3";
                break;
        }
        return at;
    }

}
